<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    public function userList($search = ""){
        if($search != ''){
            $allUser = User::where('display_name', 'like', '%'.$search.'%')->paginate(6);
        }else{
            $allUser = User::paginate(6);
        }
        return view('admin.user',['items'=>$allUser,'type'=>'list','searchWord'=>$search]);
    }
    public function userHandler($type,$id = ''){
        if ($type == 'add'){
            if ($id != ''){
                return redirect('/admin/user/edit/'.$id);
            }
            return view('admin.user',['type'=>$type,'id'=>'new']);
        }else if($type == 'edit'){
            if ($id == ''){
                return redirect('/admin/user/add');
            }
            $user = User::findOrFail($id);
            return view('admin.user',['type'=>$type,'id'=>$id,'username'=>$user->display_name,'email'=>$user->email]);
        }
    }
    public function saveUser(Request $request){
        $id = $request['id'];
        $userName = $request['username'];
        $password = $request['password'];
        $repassword = $request['repassword'];
        $email = $request['email'];
        if ($userName == ''){
            return response()->json(['res'=>false,'msg'=>'请输入用户名']);
        }else if($password == ''){
            return response()->json(['res'=>false,'msg'=>'请输入密码']);
        }else if($email == ''){
            return response()->json(['res'=>false,'msg'=>'请输入邮箱']);
        }else if($password != $repassword){
            return response()->json(['res'=>false,'msg'=>'两次密码不一致']);
        }
        $role = 'admin';
        if ($id == 'new'){
            $user = new User();
        }else{
            $user = User::findOrFail($id);
        }
        $user->display_name = $userName;
        $user->password = bcrypt($password);
        $user->role = $role;
        $user->email = $email;
        $user->save();
        return response()->json(['res'=>true,'msg'=>'保存成功']);
    }
    public function deleteUser(Request $request){
        $id = $request['id'];
        $user = User::find($id)->delete();
        return response()->json(['res'=>true,'msg'=>'删除成功']);
    }
}
